package com.i.picservice.controller;

import com.i.piccommon.constant.ApiResponse;
import com.i.piccommon.domain.Category;
import com.i.piccommon.domain.PhotoGraph;
import com.i.piccommon.util.MinioUtil;
import com.i.picservice.client.CategoryFeignClient;
import com.i.picservice.service.IPhotoGraphService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/10/25
 */
@RestController
@RequiredArgsConstructor
public class PhotoGraphController {
    private final IPhotoGraphService photoGraphService;
    private final MinioUtil minioUtil;
    private final CategoryFeignClient categoryFeignClient;
    /**
     * 查询全部图片
     */
    @GetMapping
    public ApiResponse<List<PhotoGraph>> getPhotoGraphAll(){
        List<Category> categorys = categoryFeignClient.categorys();
        System.out.println(categorys);
        return ApiResponse.ok(photoGraphService.list());
    }

    @RequestMapping("/upload")
    public ApiResponse<Object> uploadImage(MultipartFile file, String[] categorys) throws IOException {
        PhotoGraph photoGraph = new PhotoGraph();
        List<Integer> list = Arrays.stream(categorys).map(Integer::valueOf).toList();
        String fileName = UUID.randomUUID().toString();
        minioUtil.upload(file,fileName);
        photoGraph.setUrl(minioUtil.getFileUrl(fileName));
        boolean save = photoGraphService.uploadImage(photoGraph);
        if(save) {
            List<Map<String, Integer>> collect = list.stream().map(l -> {
                Map<String, Integer> map = new HashMap<>();
                map.put("pid", photoGraph.getPid());
                map.put("cid", l);
                return map;
            }).toList();
            photoGraphService.insertByPhotoCS(collect);
            return ApiResponse.ok(photoGraphService);
        }
        return ApiResponse.fail();
    }

    @RequestMapping("/page")
    public ApiResponse<Object> getPhotoGraphPage(@RequestBody Category vo) {
        if(vo.getClassification() == null || "".equals(vo.getClassification())) {
            System.out.println("----------------------------");
            return ApiResponse.ok(photoGraphService.getPage(vo));
        }else {
            return ApiResponse.ok(categoryFeignClient.searchPhotoByCategory(vo));
        }
    }

    @RequestMapping("/{id}")
    public ApiResponse<PhotoGraph> getPhotoGraphById(@PathVariable Integer id) {
        return ApiResponse.ok(photoGraphService.lambdaQuery().eq(PhotoGraph::getPid,id).one());
    }
}
